﻿using OmixJsonServer.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace OmixJsonServer.Extensions
{
    public static class HttpRequestExtension
    {
        public static dynamic MapToType(this HttpRequest request, Type toType, object currentObject=null)
        {
            try
            {
                string columnName = "";

                object obj = null;

                if (currentObject == null)
                {
                     obj= Activator.CreateInstance(toType);
                }
                else
                {
                    obj = currentObject;
                }
                //PropertyInfo[] pis = ReflectionHelper.GetProperties(obj);
                PropertyInfo[] pis = toType.GetProperties();
                foreach (var p in pis)
                {
                    columnName = p.Name;
                    if (request[columnName] != null)
                    {
                        ReflectionHelper.SetPropertyValue(obj, p.Name, request[columnName].ToString());
                    }
                }
                return obj;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
    }
}